//
//  TransmutationView.m
//  SecondPage
//
//  Created by xiong qi on 13-4-16.
//  Copyright (c) 2013年 winston. All rights reserved.
//

#import "TransmutationView.h"
#import "../../ResourceLoader/ResourceLoader/ResourceLoader.h"
#import "../../ResourceLoader/ResourceLoader/TemplateFactory.h"
#import "MediaView.h"

#define AnimationDuration 0.4

@implementation TransmutationView


@synthesize currentType;
@synthesize currentMiddleView;
@synthesize contentArray,RootPath;
@synthesize parentView;

- (id)initWithFrame:(CGRect)frame RootPath:(NSString *)path Files:(NSArray *)array
{
    self = [super initWithFrame:frame];
    if (self)
    {
        originRect = frame;
        self.pagingEnabled = YES;
        self.decelerationRate = 0.1;

        self.delegate = self;
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
        
        self.RootPath = path;
        self.contentArray = array;
        
    }
    return self;
}

-(void)renderTemplate
{
    if(contentArray&&[contentArray count]>0)
    {
        CGFloat centerX = 0;
        CGFloat centerY = 0;
        
        self.contentSize = CGSizeMake((([contentArray count]-1)/6+1)*self.frame.size.width,self.frame.size.height);
        
        NSMutableArray * timelinearray = [NSMutableArray array];
        
        for(NSInteger i=0;i<[contentArray count];i++)
        {
            NSString * tplName = [contentArray objectAtIndex:i];

            TemplateView * tView = [[TemplateFactory getInstance] createViewByTemplateFileName:tplName RootPath:self.RootPath];
            [self addSubview:tView];
            [tView release];
            tView.delegate = self;
            tView.tag = i+100;
            
            [timelinearray addObject:tView.textString];
            
            //一面放6个，放不下的放到另一面
            int page = i/6;
            int row = (i%6)/3;
            int col = (i%6)%3;
            
            //间隙横向20 纵向20
            centerX = page * self.frame.size.width + TemplateSpaceX + col*(TemplateWidth+TemplateSpaceX)+TemplateWidth/2;
            centerY = row * (TemplateHeight+TemplateSpaceY)+TemplateTopSpace+TemplateHeight/2;
            
//            DFLog(@"%@ %f %f",tplName,centerX,centerY);
            
            tView.center = CGPointMake(centerX, centerY);
            [tView renderTemplate];
        }
    
        if ([parentView respondsToSelector:@selector(RefreshTimeLine:)]) {
            [parentView performSelector:@selector(RefreshTimeLine:) withObject:timelinearray];
        }
    }
}

#pragma mark----TemplateViewDelegate
-(void)ViewBeTouch:(TemplateView *)view
{
    if(currentType == 0)
    {
        [self TouchSmall:view];
    }
    else if(currentType == 1)
    {
        [self TouchMiddle:view];
    }
}


-(void)TouchSmall:(TemplateView *)view
{
    isCanMove = NO;
    currentType = 1;
    self.currentMiddleView = view;
    self.pagingEnabled = NO;
    self.clipsToBounds = NO;
    [self bringSubviewToFront:view];
    int index = view.tag;
    int largeviewwidth  = TemplateWidthMiddle;
    int largeviewheight = TemplateHeightMiddle;
    int pageindex = (index-100)/6;
    
    //将看不见的视图置为隐藏状态
    for (NSInteger i=0;i<[contentArray count];i++) {
        UIView * tempview = [self viewWithTag:i+100];
        if ((tempview.tag-100)/6 != pageindex) {
            tempview.alpha = 0;
        }
    }
    
    self.userInteractionEnabled = NO;
    [UIView animateWithDuration:AnimationDuration
                     animations:^{
                         //此处减的20需要与下面self.frame的高度减40对应上
                         view.frame = CGRectMake(pageindex*self.frame.size.width +(self.frame.size.width-largeviewwidth)/2, (self.frame.size.height-largeviewheight)/2-20, largeviewwidth, largeviewheight);
                         [view TransmutationMiddle];
                     }
                     completion:^(BOOL finished){
                         
                         UIView * parentview = self.superview;
                         
                         self.frame = CGRectMake(0, 0, parentview.frame.size.width, parentview.frame.size.height-40);

                         self.contentSize = CGSizeMake((([contentArray count]-1)*(TemplateWidth+TemplateSpaceX)+self.frame.size.width+TemplateWidth/2), self.frame.size.height);

                         if (index == 100) {
                             view.center = self.center;
                         }
                         else
                         {
                             view.center = CGPointMake(self.center.x-(TemplateHeightMiddle-TemplateWidth)/2 + (index-101)*(TemplateWidth+TemplateSpaceX)+TemplateWidthMiddle/2+TemplateSpaceX+TemplateWidth/2, self.center.y);
                         }
                         
                         self.contentOffset = CGPointMake(view.center.x-self.superview.center.x, 0);
                         
                         UIView * tempview;
                         int indexspace = 0;
                         int offsetX = 0;
                         for (NSInteger i=0;i<[contentArray count];i++) {
                             tempview = [self viewWithTag:i+100];
                             indexspace = tempview.tag-index;
                             if (indexspace >0) {
                                 offsetX = (tempview.tag-index)*(TemplateWidth+TemplateSpaceX)+(largeviewwidth-TemplateWidth)/2;
                             }
                             else if(indexspace <0)
                             {
                                 offsetX = -((index - tempview.tag)*(TemplateWidth+TemplateSpaceX)+(largeviewwidth-TemplateWidth)/2);
                             }
                             else
                             {
                                 continue;
                             }
                             tempview.alpha = 0;
                             tempview.center = CGPointMake(view.center.x + offsetX, view.center.y-YCenterOffset);
                         }
                         
                         
                         
                         [UIView animateWithDuration:AnimationDuration
                                          animations:^{
                                              
                                              UIView * tempview;
                                              for (NSInteger i=0;i<[contentArray count];i++) {
                                                  tempview = [self viewWithTag:i+100];
                                                  if (tempview != view) {
                                                      tempview.alpha = 1.0;
                                                  }
                                              }
                                              
                                              if ([parentView respondsToSelector:@selector(SetTimeLineAlpha:)]) {
                                                  [parentView performSelector:@selector(SetTimeLineAlpha:) withObject:[NSNumber numberWithFloat:1.0]];
                                              }
                                          }
                                          completion:^(BOOL finished){
                                              isCanMove = YES;
                                              self.userInteractionEnabled = YES;
                                          }];
                         
                         
                     }];
}

-(void)TouchMiddle:(TemplateView *)view
{
    if (view == currentMiddleView) {
        [self InitMediaView];
    }
    else
    {
        [self MoveToView:view];
    }
        
}


#pragma mark ----UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (isCanMove) {
        [self ChangeFrame:scrollView.contentOffset.x];
    }

}

#pragma mark----Touch
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (currentType == 1) {
        currentType = 0;
        isCanMove = NO;
        self.userInteractionEnabled = NO;
        [UIView animateWithDuration:AnimationDuration
                         animations:^{
                             
                            currentMiddleView.bounds = CGRectMake(0, 0, TemplateWidth, TemplateHeight);
                             [currentMiddleView TransmutationSmall];
                             
                             TemplateView * tempview = nil;
                             for(NSInteger i=0;i<[contentArray count];i++)
                             {
                                 tempview = (TemplateView *)[self viewWithTag:100+i];
                                 tempview.alpha = 0;
                             }
                             if ([parentView respondsToSelector:@selector(SetTimeLineAlpha:)]) {
                                 [parentView performSelector:@selector(SetTimeLineAlpha:) withObject:[NSNumber numberWithFloat:0]];
                             }
                         }
                         completion:^(BOOL finished){

                             self.pagingEnabled = YES;
                             self.clipsToBounds = YES;
                             self.frame = originRect;
                             self.contentSize = CGSizeMake((([contentArray count]-1)/6+1)*self.frame.size.width,self.frame.size.height);
                             self.contentOffset = CGPointMake(((currentMiddleView.tag-100)/6)*originRect.size.width, 0);
                             
                             TemplateView * tempview = nil;
                             float centerX = 0;
                             float centerY = 0;
                             for(NSInteger i=0;i<[contentArray count];i++)
                             {
                                 tempview = (TemplateView *)[self viewWithTag:100+i];
                                 
                                 //一面放6个，放不下的放到另一面
                                 int page = i/6;
                                 int row = (i%6)/3;
                                 int col = (i%6)%3;
                                 
                                 //间隙横向20 纵向20
                                 centerX = page * self.frame.size.width + TemplateSpaceX + col*(TemplateWidth+TemplateSpaceX)+TemplateWidth/2;
                                 centerY = row * (TemplateHeight+TemplateSpaceY)+TemplateTopSpace+TemplateHeight/2;
                                 
                                 tempview.center = CGPointMake(centerX, centerY);
                             }
                             
                             currentMiddleView = nil;
                             
                             [UIView animateWithDuration:AnimationDuration
                                              animations:^{
                                                  
                                                  TemplateView * tempview = nil;
                                                  for(NSInteger i=0;i<[contentArray count];i++)
                                                  {
                                                      tempview = (TemplateView *)[self viewWithTag:100+i];
                                                      tempview.alpha = 1.0;
                                                      
                                                  }
                                                  
                                              }
                                              completion:^(BOOL finished){
                                                  self.userInteractionEnabled = YES;
                                                  
                                              }];
                         }];
        
    }
}

#pragma  mark ----Other
-(void)MoveToView:(TemplateView *)view
{
    if (view.tag == 100) {
        [self setContentOffset:CGPointZero animated:YES];
    }
    else if(view.tag == [contentArray count]+99)
    {
        [self setContentOffset:CGPointMake(self.contentSize.width-self.frame.size.width, 0) animated:YES];
    }
    else
    {
        [self setContentOffset:CGPointMake(self.center.x-(TemplateHeightMiddle-TemplateWidth)/2 + (view.tag-101)*(TemplateWidth+TemplateSpaceX)+TemplateWidthMiddle/2+TemplateSpaceX+TemplateWidth/2-self.superview.center.x, 0) animated:YES];
    }
}


-(void)ChangeFrame:(float)offsetx
{
    int spaceX = offsetx+self.frame.size.width/2;
    //左滑
    if (spaceX-TemplateWidthMiddle/4>currentMiddleView.center.x) {
        
        if(currentMiddleView.tag<[contentArray count]+99)
        {
            TemplateView * nextview = (TemplateView *)[self viewWithTag:currentMiddleView.tag+1];
            [UIView animateWithDuration:AnimationDuration
                             animations:^{
                                 nextview.bounds = CGRectMake(0, 0, TemplateWidthMiddle, TemplateHeightMiddle);
                                 currentMiddleView.bounds = CGRectMake(0, 0, TemplateWidth, TemplateHeight);
                                 
                                 //当前视图是第一个视图
                                 if (currentMiddleView.tag == 100) {
                                     
                                     currentMiddleView.center = CGPointMake(self.center.x-(TemplateHeightMiddle-TemplateWidth)/2, self.center.y-YCenterOffset);
                                     nextview.center = CGPointMake(currentMiddleView.center.x + ((TemplateWidth+TemplateWidthMiddle)/2+TemplateSpaceX), self.center.y);
                                     
                                     TemplateView * tempview = nil;
                                     for (int i=2; i<[contentArray count]; i++) {
                                         
                                         tempview = (TemplateView *)[self viewWithTag:100+i];
                                         UIView * preview = [self viewWithTag:i+99];
                                         
                                         if (preview == nextview) {

                                             tempview.center = CGPointMake(nextview.center.x + ((TemplateWidth+TemplateWidthMiddle)/2+TemplateSpaceX), self.center.y-YCenterOffset);
                                         }
                                         else
                                         {

                                             tempview.center = CGPointMake(preview.center.x+(TemplateWidth+TemplateSpaceX), self.center.y-YCenterOffset);
                                         }
                                     }
                                 }
                                 else
                                 {
                                     UIView * preview = [self viewWithTag:currentMiddleView.tag-1];

                                     currentMiddleView.center = CGPointMake(preview.center.x+(TemplateWidth+TemplateSpaceX), self.center.y-YCenterOffset);
                                     nextview.center = CGPointMake(currentMiddleView.center.x + ((TemplateWidth+TemplateWidthMiddle)/2+TemplateSpaceX), self.center.y);
                                 }

                                 [currentMiddleView TransmutationSmall];
                                 [nextview TransmutationMiddle];
                                 self.currentMiddleView = nextview;
                             }
                             completion:^(BOOL finished){
                                 
                             }];
        }
    }
    //右滑
    else if(currentMiddleView.center.x>spaceX+TemplateWidthMiddle/4)
    {
        if (currentMiddleView.tag != 100) {
            
            [UIView animateWithDuration:AnimationDuration
                             animations:^{

                                 TemplateView * preview = (TemplateView *)[self viewWithTag:currentMiddleView.tag-1];
                                 preview.bounds = CGRectMake(0, 0, TemplateWidthMiddle, TemplateHeightMiddle);
                                 currentMiddleView.bounds = CGRectMake(0, 0, TemplateWidth, TemplateHeight);
                                 
                                 //如果当前是最后一个视图
                                 if (currentMiddleView.tag == [contentArray count]+99) {

                                     currentMiddleView.center = CGPointMake(self.contentSize.width-(self.frame.size.width/2 - (TemplateHeightMiddle-TemplateWidth)/2), self.center.y-YCenterOffset);
                                     
                                     preview.center = CGPointMake(currentMiddleView.center.x - ((TemplateWidth+TemplateWidthMiddle)/2+TemplateSpaceX), self.center.y);
                                     
                                     TemplateView * tempview = nil;
                                     for (int i=[contentArray count]-3; i>=0; i--) {
                                         
                                         tempview = (TemplateView *)[self viewWithTag:100+i];
                                         UIView * nextview = [self viewWithTag:101+i];
                                         
                                         if (preview == nextview) {

                                             tempview.center = CGPointMake(preview.center.x - ((TemplateWidth+TemplateWidthMiddle)/2+TemplateSpaceX), self.center.y-YCenterOffset);
                                         }
                                         else
                                         {

                                             tempview.center = CGPointMake(nextview.center.x-(TemplateWidth+TemplateSpaceX), self.center.y-YCenterOffset);
                                         }
                                     }

                                     
                                 }
                                 else
                                 {
                                     UIView * nextview = [self viewWithTag:currentMiddleView.tag+1];

                                     currentMiddleView.center = CGPointMake(nextview.center.x-(TemplateWidth+TemplateSpaceX), self.center.y-YCenterOffset);
                                     preview.center = CGPointMake(currentMiddleView.center.x - ((TemplateWidth+TemplateWidthMiddle)/2+TemplateSpaceX), self.center.y);
                                     
                                  }

                                 [currentMiddleView TransmutationSmall];
                                 [preview TransmutationMiddle];
                                 self.currentMiddleView = preview;
                             }
                             completion:^(BOOL finished){
                             }];
        }
        
        
    }
}

-(void)InitMediaView
{
    if (mediaview == nil) {
        mediaview = [[MediaView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
    }
    mediaview.alpha = 0;
    
    if(currentMiddleView.playPath == nil)
    {
        return;
    }
    
    if (currentMiddleView.type == ImageTemplateType) {
        [mediaview Refresh:currentMiddleView.playPath Type:0];
    }
    else if(currentMiddleView.type == VidelTemplateType)
    {
        [mediaview Refresh:currentMiddleView.playPath Type:1];
        return;
    }
    else if(currentMiddleView.type == MixTemplateType)
    {
        [mediaview Refresh:currentMiddleView.playPath Type:0];
    }
    
    
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [window.rootViewController.view addSubview:mediaview];
    
    [self ShowMediaView];
}

-(void)ShowMediaView
{
    [UIView animateWithDuration:AnimationDuration
                     animations:^{
                         
                         mediaview.alpha = 1.0;
                     }
                     completion:^(BOOL finished){
                         
                         
                     }];
}

-(void)dealloc
{
    self.currentMiddleView = nil;
    self.RootPath = nil;
    self.contentArray = nil;
    self.parentView = nil;
    SafeRelease(mediaview);
    [super dealloc];
}

@end
